package org.example.service;

import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.example.dto.ProductSpecDTO;
import org.example.entity.*;
import org.example.mapper.Shanpinfelemapper;
import org.example.mapper.Shanpinmapper;
import org.example.mapper.Shouchanmapper;
import org.example.mapper.Wdzjmapper;
import org.example.result.PageResult;
import org.example.result.Pages;
import org.example.vo.CategoryVO;
import org.example.vo.ProductSpecVO;
import org.example.vo.ProductVO;
import org.example.vo.ShippingVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class ShanpinService {
    @Autowired
    Shanpinmapper shanpinmapper;
    @Autowired
    Shanpinfelemapper shanpinfelemapper;
    @Autowired
    private Wdzjmapper wdzjmapper;
    @Autowired
    private Shouchanmapper shouchanmapper;

    /**
     * 商品分页查询
     *
     * @param page
     * @return
     */
    public PageResult pageQuery(Pages page) {
        //开始分页查询
        PageHelper.startPage(page.getCurrentPage(), page.getPagesize());

        com.github.pagehelper.Page<Shanpin> pages = shanpinmapper.pageQuery(page);

        long total = pages.getTotal();
        List<Shanpin> records = pages.getResult();

        return new PageResult(total, records);
    }

    /**
     * 新增商品
     *
     * @param produc
     * @param images
     * @param i
     * @param background
     */
    public void xz(Product produc, MultipartFile[] images, int i, MultipartFile background) {


        String n = background.getOriginalFilename();
        String ne = UUID.randomUUID().toString() + n.substring(n.lastIndexOf("."));

        if (background.getSize() == 0) {
            // 占位文件，跳过处理
          produc.setImage(background.getOriginalFilename());
        } else {
            try {
                background.transferTo(new File("D:/wenjian/java/image/" + ne));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            produc.setImage("http://localhost:8080/image/" + ne);
        }

        produc.setCreateTime(LocalDateTime.now());
        produc.setUpdateTime(LocalDateTime.now());
        produc.setStatus(1);

        shanpinmapper.xz(produc);
        shanpinmapper.xzproduc(produc);

        for (MultipartFile m : images) {
            if ("placeholder.txt".equals(m.getOriginalFilename())
                    && m.getSize() == 0) {
                // 占位文件，跳过处理
                shanpinmapper.xgimage(i, produc.getId());
                continue;
            }

            String name = m.getOriginalFilename();
            String newname = UUID.randomUUID().toString() + name.substring(name.lastIndexOf("."));

            try {
                m.transferTo(new File("D:/wenjian/java/image/" + newname));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            shanpinmapper.xzimgae(produc.getId(), "http://localhost:8080/image/" + newname);
        }
        produc.getCategory().setIdint(produc.getId());
        shanpinmapper.xzcategory(produc.getCategory());

        for (Spec s : produc.getCategory().getSpecs()) {
            ProductSpecDTO productSpecDTO = new ProductSpecDTO();
            productSpecDTO.setName(s.getName());
            productSpecDTO.setIdint(produc.getCategory().getIdint());
            productSpecDTO.setShanpinid(produc.getId());
            shanpinmapper.xzspec(productSpecDTO);
            for (String p : s.getOptions())
                shanpinmapper.xzoptions(produc.getId(), p, productSpecDTO.getId());
        }


        //商品分类
        int shu = shanpinfelemapper.feleshucx(produc.getSpecs(), produc.getUsername()) + 1;
        shanpinfelemapper.feleshuxg(produc.getSpecs(), produc.getUsername(), shu);
    }


    /**
     * 商品修改查询
     *
     * @param id
     * @return
     */
    public ProductVO xgcx(int id) {
        ProductVO productVO = new ProductVO();
        Product product = shanpinmapper.cxproduct(id);
        Product product1 = shanpinfelemapper.cxshanpin(id);
        productVO.setUsername(product1.getUsername());
        productVO.setName(product.getName());
        productVO.setPrice(product.getPrice());
        productVO.setStock(product.getStock());
        productVO.setWeight(product.getWeight());

        productVO.setImagezhu(product1.getImage());

        ShippingVO shippingVO = new ShippingVO();
        shippingVO.setLocation(product.getLocation());
        shippingVO.setTemplate(String.valueOf(product.getTemplate()));

        productVO.setShipping(shippingVO);


        productVO.setSpecs(shanpinmapper.cxfele(id));


        CategoryVO c = shanpinmapper.cxcategory(id);

        c.setSpecs(shanpinmapper.cxspec(c.getId(), id));
        for (ProductSpecVO s : c.getSpecs()) {
            s.setOptions(shanpinmapper.cxoptions(s.getId()));
        }


        productVO.setCategory(c);


        List<Image> images = new ArrayList<>();
        List<String> imageurl = shanpinmapper.cximage(id);
        for (String u : imageurl) {
            Image image = new Image();
            image.setUrl(u);
            images.add(image);
        }
        productVO.setImages(images);

        productVO.setId(id);
        return productVO;
    }

    /**
     * 修改删除
     *
     * @param id
     */
    public void xgsc(int id ,int pd) {

        Shanpin shanpin = shanpinmapper.cxid(id);

        int shu = shanpinfelemapper.feleshucx(shanpin.getShanpinfeleName(), shanpin.getUsername());
        shanpinfelemapper.feleshuxg(shanpin.getShanpinfeleName(), shanpin.getUsername(), shu - 1);

        shanpinmapper.xgscshanpin(id);
        shanpinmapper.xgscproduct(id);
        shanpinmapper.xgsccategory(id);
        if(pd==1) {
            shanpinmapper.xgdanscimage(id);
        }
        shanpinmapper.xgscspec(id);
        shanpinmapper.xgscoptions(id);

        wdzjmapper.scpl(id);
        shouchanmapper.scpl(id);
    }

    //image
    public void xgscimage(String url) {
        shanpinmapper.xgscimage(url);
    }

    /**
     * 修改状态
     *
     * @param product
     */
    public void xgzt(Product product) {
        product.setStatus(product.getStatus() == 0 ? 1 : 0);
        shanpinmapper.xgzt(product);
    }


    /**
     * 批量删除
     *
     * @param name
     * @param status
     * @param felename
     * @param username
     */
    public void xgplsc(String name, String status, String felename, String username) {
        List<Integer> ids = shanpinmapper.plsccx(name, status, felename, username);
        for (int id : ids) {
            xgsc(id,1);

        }
    }

    /**
     * 主页商品查询
     * @return
     */
    public List<Shanpin> zhuyeshanpincx() {
        List<Product> productList=shanpinmapper.productList();
        List<Shanpin> shanpinList=new ArrayList<>();
        for(Product p:productList){
            Shanpin shanpin=shanpinmapper.cxid(p.getShanpinId());
            if(shanpin.getStatus()==1) {
                shanpin.setYingfe(p.getTemplate());
                shanpinList.add(shanpin);
            }
        }
        return  shanpinList;
    }

    /**
     * 照片查询
     * @param id
     * @return
     */
    public String[] zhaopiancx(int id) {
        Shanpin shanpin=shanpinmapper.cxid(id);
        String[] string=shanpinmapper.zhaopian(id);
        String[] string1=new String[string.length+1];
        for(int i=0;i<string.length;i++){
            string1[i+1]=string[i];
        }
        string1[0]=shanpin.getImage();
        return string1;
    }

    /**
     * 商品店铺查询
     * @return
     */
    public List<Shanpin> shanpindianpucx(int id) {
        Shanpin shanpin1=shanpinmapper.cxid(id);
        List<Product> productList=shanpinmapper.productList();
        List<Shanpin> shanpinList=new ArrayList<>();
        for(Product p:productList){
            if(p.getShanpinId()==id)
                continue;
            Shanpin shanpin=shanpinmapper.cxtjid(p.getShanpinId(),shanpin1.getUsername());
            if(shanpin==null)
                continue;
            shanpin.setYingfe(p.getTemplate());
            shanpinList.add(shanpin);
        }
        return  shanpinList;
    }

    /**
     * 相关商品查询
     * @param id
     * @return
     */
    public List<Shanpin> shanpinxgcx(int id) {

        Shanpin shanpin1=shanpinmapper.cxid(id);
        List<Product> productList=shanpinmapper.productList();
        List<Shanpin> shanpinList=new ArrayList<>();
        for(Product p:productList){
            if(p.getShanpinId()==id)
                continue;
            Shanpin shanpin=shanpinmapper.cxtxgjid(p.getShanpinId(),shanpin1.getShanpinfeleName());
            if(shanpin==null)
                continue;
            shanpin.setYingfe(p.getTemplate());
            shanpinList.add(shanpin);
        }
        return  shanpinList;
    }

    /**
     * 商品搜索查询
     * @param souso
     * @return
     */
    public List<Shanpin> zhuyeshanpinsousocx(String souso) {

        List<Product> productList=shanpinmapper.productList();
        List<Shanpin> shanpinList=new ArrayList<>();
        for(Product p:productList){
            Shanpin shanpin=shanpinmapper.cxsousoid(p.getShanpinId(),souso);
            if(shanpin!=null) {
                if (shanpin.getStatus() == 1) {
                    shanpin.setYingfe(p.getTemplate());
                    shanpinList.add(shanpin);
                }
            }
        }
        return  shanpinList;
    }

    /**
     * 修改数目
     * @param shanpinid
     */
    public void xgshu(int shanpinid) {
        shanpinmapper.xgshu(shanpinid);
        shanpinmapper.xgshuproduct(shanpinid);
    }
}
